package com.yinian.server.service.impl;

import com.yinian.common.constant.MessageConstant;
import com.yinian.common.exception.AccountNotFoundException;
import com.yinian.common.exception.PasswordErrorException;
import com.yinian.common.utils.MailService;
import com.yinian.pojo.dto.UserLoginDTO;
import com.yinian.pojo.dto.UserRegisterDTO;
import com.yinian.pojo.dto.UserUpdateInformationDTO;
import com.yinian.pojo.dto.VerificationCodeDTO;
import com.yinian.pojo.entity.User;
import com.yinian.pojo.vo.UserRegisterVO;
import com.yinian.server.mapper.UserMapper;
import com.yinian.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MailService mailService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        String email = userLoginDTO.getEmail();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user =  userMapper.getByEmail(email);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return user;
    }

    @Override
    public User register(UserRegisterDTO userRegisterDTO) {
        User user = userMapper.selectByEmail(userRegisterDTO.getEmail());


        return user;
    }

    @Override
    public void save(User user) {
        userMapper.insertUser(user);
    }

    @Override
    public void sendVerificationCode(VerificationCodeDTO verificationCodeDTO) {
        String email = verificationCodeDTO.getEmail();
        log.info("获取邮箱：{}", email);
        String code = String.format("%06d", ThreadLocalRandom.current().nextInt(1000000));
        mailService.sendTextMailMessage(
                email,
                "颐年验证码",
                "验证码可以用来登录账号，请谨慎保存：" + code
        );
        redisTemplate.opsForValue().set(email + "_code",code,500l, TimeUnit.SECONDS);
    }

    @Override
    public void updateUserInformation(UserUpdateInformationDTO userUpdateInformationDTO) {
        userMapper.updateUserInformation(userUpdateInformationDTO);
    }

}
